;; 使用Emacs的Project功能

(when (maybe-require-package 'project)
  ;; (global-set-key (kbd "<f9>") project-prefix-map)
  ;; (setq project-switch-commands '(("<f9>" . project-switch-project)
  ;;                                 ("j" . project-find-file-in-directory)
  ;;                                 )))

  (with-eval-after-load 'project
    ;; project.el 中，默认只支持 VC 中的 Git，即 project-try-vc，但可以自定义找根目录的方式，配置如下：
    (defcustom my/project-root-markers
      '("Cargo.toml" "compile_commands.json" "compile_flags.txt"
        "project.clj" ".project" ".root")
      "Files or directories that indicate the root of a project."
      :type '(repeat string)
      :group 'project)

    (defun my/project-root-p (path)
      "Check if the current PATH has any of the project root markers."
      (catch 'found
        (dolist (marker my/project-root-markers)
          (when (file-exists-p (concat path marker))
            (throw 'found marker)))))

    (defun my/project-find-root (path)
      "Search up the PATH for `my/project-root-markers'."
      (when-let ((root (locate-dominating-file path #'my/project-root-p)))
        (cons 'transient (expand-file-name root))))

    (push #'my/project-find-root project-find-functions)

    ;; 查找文件是非常高频的操作，使用 fd 来代替 find，速度更快
    (defun my/project-files-in-directory (dir)
      "Use `fd' to list files in DIR."
      (let* ((default-directory dir)
             (localdir (file-local-name (expand-file-name dir)))
             (command (format "fd -H -t f -0 . %s" localdir)))
        (project--remote-file-names
         (sort (split-string (shell-command-to-string command) "\0" t)
               #'string<))))

    (cl-defmethod project-files ((project (head local)) &optional dirs)
      "Override `project-files' to use `fd' in local projects."
      (mapcan #'my/project-files-in-directory
              (or dirs (list (project-root project)))))
    ))

(provide 'init-project)
